package com.zfh.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zfh.entity.User;
import com.zfh.service.UserService;
import com.zfh.service.UserServiceImpl1;

@WebServlet("/user/addUser")
public class UserAddController extends HttpServlet{
	
	private static UserService userService = new UserServiceImpl1();
	
	
	/**
	 *	<h1>// Servlet服务接口：接请求<h1>
	 *	<li> 1 接请求
	 *	<li> 2 调业务
	 *	<li> 3给响应，做跳转
	 *	
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);		
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		// 解决中文乱码
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		// 拿参数
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String gender = request.getParameter("gender");
		String bir = request.getParameter("bir");
		String score = request.getParameter("score");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date userBir = null;
		try {
			userBir = sdf.parse(bir);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		int userScore = Integer.parseInt(score);
		User user = new User(id, name, gender, userBir, userScore);
		System.out.println(user);
		try {
//					int a = 9/0;	// 这个异常的引入，要前置，否则，在forward后就无法再跳转了
			// 先入库
			userService.save(user);
			System.out.println("入库成功");
			// 再查看，直接转查看业务即可，在更新业务完成后，建议重定向到查看页面
//			request.getRequestDispatcher("/user/getAll").forward(request, response);
			response.sendRedirect("getAll");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/showError.jsp").forward(request, response);
		}
	}
	
	
	// 单元测试： 对用户业务逻辑进行测试
	public static void testUserService() {
		List<User> users = userService.getAll();
		users.forEach(u->{
			System.out.println(u);
		});
	}
	
	// 单元测试驱动
	public static void main(String[] args) {
		testUserService();
	}

}
